// pages/index/city.js
const CityService = require('../../services/city');
const LocationService = require('../../services/location');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cityList:[],
    currentCity:{},
    isLocating: false,
    locationError: '',
    locatedCity: null, // 定位到的城市
    showLocationResult: false, // 是否显示定位结果
    locationAddress: '' // 定位的详细地址
  },

  async loadCityList(){
    const res = await CityService.getCityList();
    if(res.success){
      this.setData({
        cityList:res.data
      });
    }
  },

  /**
   * 格式化地址信息
   * @param {Object} addressInfo 逆地理编码返回的地址信息
   * @returns {string} 格式化后的地址字符串
   */
  formatAddress(addressInfo) {
    if (!addressInfo || !addressInfo.address_component) {
      return '地址信息获取失败';
    }

    const component = addressInfo.address_component;
    let address = '';

    // 构建详细地址
    if (component.province) {
      address += component.province;
    }
    if (component.city && component.city !== component.province) {
      address += component.city;
    }
    if (component.district) {
      address += component.district;
    }
    if (component.street) {
      address += component.street;
    }
    if (component.street_number) {
      address += component.street_number;
    }

    // 如果没有详细地址，使用formatted_addresses中的信息
    if (!address && addressInfo.formatted_addresses) {
      const formatted = addressInfo.formatted_addresses;
      if (formatted.recommend) {
        address = formatted.recommend;
      } else if (formatted.rough) {
        address = formatted.rough;
      }
    }

    return address || '地址信息不完整';
  },

  /**
   * 自动定位获取当前城市
   */
  async getCurrentCityByLocation() {
    try {
      this.setData({
        isLocating: true,
        locationError: ''
      });

      // 检查权限
      const hasAuth = await LocationService.requestLocationAuth();
      if (!hasAuth) {
        this.setData({
          isLocating: false,
          locationError: '需要位置权限才能自动定位城市'
        });
        return;
      }

      // 获取当前位置
      const locationRes = await LocationService.getCurrentLocation({
        showLoading: false
      });

      if (!locationRes.success) {
        throw new Error(locationRes.message);
      }

      const { latitude, longitude } = locationRes.data;


      let matchedCity = null;

      try {
        
        // 首先尝试逆地理编码获取地址信息
        const geocodeRes = await LocationService.reverseGeocode(latitude, longitude);
        
        if (geocodeRes.success) {
          const addressInfo = geocodeRes.data;

          console.log('addressInfo:', addressInfo);
          
          // 保存详细地址信息
          const address = this.formatAddress(addressInfo);
          this.setData({
            locationAddress: address
          });
          
          // 优先使用adcode进行精确匹配
          const adcode = LocationService.getAdcodeFromGeocode(addressInfo);
          console.log('adcode:', adcode);
          console.log('cityList:', this.data.cityList);
          if (adcode) {
            matchedCity = CityService.checkCityAvailabilityByAdcode(adcode, this.data.cityList);
            console.log('matchedCity:', matchedCity);
          }


        }
      } catch (geocodeError) {
        console.warn('逆地理编码失败，尝试坐标匹配:', geocodeError);
      }

      // 如果逆地理编码失败，尝试基于坐标范围匹配
      if (!matchedCity) {
        const coordinateMatchedCity = LocationService.matchCityByCoordinates(latitude, longitude, this.data.cityList);
        // 检查坐标匹配的城市是否开通
        if (coordinateMatchedCity && coordinateMatchedCity.status === 1) {
          matchedCity = coordinateMatchedCity;
        }
      }
      
      if (matchedCity) {
        // 显示定位结果，让用户确认
        this.setData({
          locatedCity: matchedCity,
          showLocationResult: true,
          locationError: ''
        });
      } else {
        this.setData({
          locationError: '当前城市暂未开通服务，请手动选择。',
          showLocationResult: false
        });
      }

    } catch (error) {
      console.error('自动定位失败:', error);
      this.setData({
        locationError: error.message || '定位失败，请手动选择城市'
      });
    } finally {
      this.setData({
        isLocating: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    await this.loadCityList();
    this.setData({
      currentCity: wx.getStorageSync('current_city')
    });
    
    // 页面加载完成后自动获取地理位置
    this.getCurrentCityByLocation();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 确认选择定位到的城市
   */
  confirmLocatedCity() {
    if (this.data.locatedCity) {
      this.setData({
        currentCity: this.data.locatedCity
      });
      wx.setStorageSync('current_city', this.data.locatedCity);
      
      wx.showToast({
        title: `已选择${this.data.locatedCity.name}`,
        icon: 'success',
        duration: 2000
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 取消选择定位到的城市
   */
  cancelLocatedCity() {
    this.setData({
      showLocationResult: false,
      locatedCity: null,
      locationAddress: ''
    });
  },

  selectCity(e){
    const city = e.currentTarget.dataset.city;
    wx.setStorageSync('current_city', city);

    wx.showToast({
      title: '切换城市成功',
      icon: 'success'
    });

    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  }
})